package org.kugua.image.impl;

import lombok.extern.slf4j.Slf4j;
import org.kugua.common.Constants;
import org.kugua.dto.SliderImage;
import org.kugua.image.ImageSelector;
import org.kugua.utils.RandomUtils;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 滑块图片加载器
 *
 * @author Administrator
 * @create 2024-09-24
 * @since 1.0.0
 */
@Slf4j
public class SliderImageSelector implements ImageSelector<SliderImage> {

    /**
     * 滑块文件名
     */
    private static final String DEFAULT_ACTIVE_SLIDER_FILE_NAME = "active";

    /**
     * 凹槽文件名
     */
    private static final String DEFAULT_FIXED_GROOVE_FILE_NAME = "fixed";

    /**
     * 缓存Map
     */
    private static final Map<String, SliderImage> SLIDER_IMAGE_MAP = new HashMap<>();

    private static final List<String> KEYS = new ArrayList<>();

    static {
        try {
            ClassPathResource classPathResource = new ClassPathResource(Constants.Path.SLIDER_PATH);
            File file = classPathResource.getFile();
            if (!file.isDirectory()) {
                log.error("SliderImageSelector: file is not a directory");
                throw new RuntimeException("SliderImageSelector: file is not a directory");
            }
            File[] files = file.listFiles();
            if (files != null) {
                for (File f : files) {
                    File[] subDirectory = f.listFiles();
                    if (subDirectory == null) {
                       continue;
                    }
                    SliderImage sliderImage = new SliderImage();
                    for (File f1 : subDirectory) {
                        if (!f1.isFile()) {
                            continue;
                        }
                        String fileName = f1.getName();
                        if (fileName.startsWith(DEFAULT_ACTIVE_SLIDER_FILE_NAME)) {
                            sliderImage.setSlider(ImageIO.read(f1));
                        } else if (fileName.startsWith(DEFAULT_FIXED_GROOVE_FILE_NAME)){
                            sliderImage.setGroove(ImageIO.read(f1));
                        }
                    }
                    SLIDER_IMAGE_MAP.put(f.getName(), sliderImage);
                    KEYS.add(f.getName());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 随机选择1个滑块配置
     *
     * @return SliderImage
     */
    @Override
    public SliderImage select() {
        int random = RandomUtils.random(KEYS.size());
        SliderImage original = SLIDER_IMAGE_MAP.get(KEYS.get(random));
        SliderImage target = new SliderImage();
        target.setSlider(copy(original.getSlider()));
        target.setGroove(copy(original.getGroove()));
        return target;
    }

}
